package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"reflect"
)

//1000以下为通用码，1000以上为用户自定义码
const (
	SuccessCode       = 10
	ErrorCode         = 20
	InternalErrorCode = 500
)

type Response struct {
	Status int         `json:"status"`
	Msg    string      `json:"msg"`
	Data   interface{} `json:"data"`
}

func ResponseError(ctx *gin.Context, err error) {
	fmt.Println(err.Error())
	resp := &Response{Status: ErrorCode, Msg: err.Error(), Data: ""}
	ctx.JSON(200, resp)
	//ctx.AbortWithError(200, err)
}

// 智能识别 参数
func ResponseSuccess(ctx *gin.Context, data ...interface{}) {
	var args []interface{}
	var res interface{}
	msg := "success!!"
	res = ""

	args = append(args, data...)

	if len(args) <= 2 && len(args) >= 0 {
		for _, arg := range args {
			if reflect.TypeOf(arg).Kind() == reflect.String {
				msg, _ = arg.(string)
				continue
			}

			if reflect.TypeOf(arg).Kind() == reflect.Struct || reflect.TypeOf(arg).Kind() == reflect.Ptr {
				res = arg
				continue
			}

		}
	} else {
		msg = "参数过多,暂不支持 form: response mw"
		res = ""
	}

	resp := &Response{Status: SuccessCode, Msg: msg, Data: res}
	ctx.JSON(200, resp)
}

//func ResponseSuccess(ctx *gin.Context, msg string, data interface{}) {
//	if len(msg) == 0 {
//		msg = "执行成功!!"
//	}
//
//	resp := &Response{Status: SuccessCode, Msg: msg, Data: data}
//	ctx.JSON(200, resp)
//}
